package com.zhong.gang.applib.base.dialog;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.zhong.gang.applib.utils.DensityUtil;
import com.zhong.gang.applib.rx.RxManager;

/**
 * Created by ajin on 2018/7/25.
 */

public abstract class BaseDialog<T extends ViewDataBinding> extends Dialog {
    private AnimatorSet animatorSet;
    public View view;
    public Context context ;
    public T bind;

    private RxManager rxManager;

    public RxManager getRxManager() {
        if (rxManager == null)
            rxManager = new RxManager();
        return rxManager;
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (rxManager != null)
            rxManager.clear();
    }

    public BaseDialog(@NonNull Context context) {
        super(context);
        this.context = context;
    }
    public BaseDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context,themeResId);
        this.context = context;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(getContext()).inflate(LayoutRes(),null);
        try {
            bind = DataBindingUtil.bind(view);
        }catch (Exception e){}
        getWindow().getDecorView().setPadding(15, 0, 15, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        int width = WindowManager.LayoutParams.FILL_PARENT;
        double widthproportion = proportion();
        if (widthproportion != 0)
            lp.width = (int) (DensityUtil.getWidth(context) *widthproportion);
        else
            lp.width = width;
        getWindow().setAttributes(lp);
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        getWindow().setGravity(Gravity());
        setContentView(view);
        initView();
    }

    @Override
    public void show() {
        super.show();
        if (view == null)
            return;
        if (animatorSet == null)
            animatorSet = new AnimatorSet();
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(view, "translationY", 300, 0).setDuration(300),
                ObjectAnimator.ofFloat(view, "alpha", 0, 1).setDuration(300 * 3 / 2));
        animatorSet.start();
    }

    @LayoutRes
    public abstract  int LayoutRes();
    public abstract void initView();
    public abstract double proportion();
    public abstract int Gravity();
}
